package com.frogs.ucenter.v1.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.ShippingAddressStatusEnum;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.system.util.UserBaseStatusEnum;
import com.frogs.system.util.UserTypeEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.TagUserRelationDao;
import com.frogs.ucenter.dao.TagUserRelationTemporaryDao;
import com.frogs.ucenter.dao.UserAccountInfoDao;
import com.frogs.ucenter.dao.UserShippingAddressDao;
import com.frogs.ucenter.dao.UserShippingAddressTemporaryDao;
import com.frogs.ucenter.entity.FollowedShippingAddressWithAreaCode;
import com.frogs.ucenter.entity.TagUserRelation;
import com.frogs.ucenter.entity.TagUserRelationTemporary;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserBaseInfo;
import com.frogs.ucenter.entity.UserLevelInfo;
import com.frogs.ucenter.entity.UserShippingAddressWithAreaCode;
import com.frogs.ucenter.util.RandomUtil;

public class UserBaseServiceImpl extends GoodsEvaluateBaseServiceImpl {	
	@Resource
	protected UserShippingAddressDao userShippingAddressDao;
	@Resource
	protected UserShippingAddressTemporaryDao userShippingAddressTemporaryDao;
	@Resource
	private TagUserRelationDao tagUserDao;
	@Resource
	private TagUserRelationTemporaryDao tagUserRelationTemporaryDao;
	@Resource
	protected UserAccountInfoDao userAccountInfoDao;
	
	protected int cacheLifeCycle = 60 * 60 * 24 * 1;
	
	protected List<Map<String, Object>> listUserTags(int userId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqUserId", userId);
		params.put("eqStatus", UserBaseStatusEnum.USER_STATUS_NOT_DELETE.getId());
		return tagUserDao.listUserTags(params);
	}
	protected List<Map<String, Object>> listFollowedTags(int userId) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqUserId", userId);
		params.put("eqStatus", UserBaseStatusEnum.USER_STATUS_NOT_DELETE.getId());
		return tagUserRelationTemporaryDao.listFollowedTags(params);
	}
	
	protected TagUserRelation relateTagUser(int userId, int tagId) throws Exception  {
		try {
			TagUserRelation tagUser = new TagUserRelation();
			tagUser.setCreateTime(tagUserDao.getCurrentTime());
			tagUser.setTagId(tagId);
			tagUser.setUserId(userId);
			tagUserDao.insert(tagUser);
			return tagUser;
		} catch (Exception e) {
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}

	protected TagUserRelationTemporary relateTagFollowed(int userId, int tagId)  throws Exception {
		try {
			TagUserRelationTemporary tagUserRelationTemporary = new TagUserRelationTemporary();
			tagUserRelationTemporary.setCreateTime(tagUserRelationTemporaryDao.getCurrentTime());
			tagUserRelationTemporary.setTagId(tagId);
			tagUserRelationTemporary.setUserId(userId);
			tagUserRelationTemporaryDao.insert(tagUserRelationTemporary);
			return tagUserRelationTemporary;
		} catch (Exception e) {
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
	}
	
	protected UserShippingAddressWithAreaCode getDefaultAddress(int userId) {
    	UserShippingAddressWithAreaCode address = null;
    	Map<String, Object> params = new HashMap<String, Object>();
    	params.put("eqUserId", userId);
    	params.put("eqIsDefault",ShippingAddressStatusEnum.STATUS_DEFAULT.getId());
    	params.put("eqStatus", ShippingAddressStatusEnum.STATUS_NOT_DELETE.getId());
    	
    	PageList<UserShippingAddressWithAreaCode> addressList = userShippingAddressDao.selectByMap(params, false);
    	if(addressList.size() != 0) {
    		address = addressList.get(0);
    	} else {
    		params.remove("eqIsDefault");
    		addressList = userShippingAddressDao.selectByMap(params, false);
    		if(addressList.size() != 0) {
    			address = addressList.get(0); 
    		}
    	}
    	parseAddressArea(address);
    	return address;
    }
	protected FollowedShippingAddressWithAreaCode getDefaultFollowedAddress(String userId) {
		FollowedShippingAddressWithAreaCode address = null;
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("eqUserId", userId);
		params.put("eqIsDefault",ShippingAddressStatusEnum.STATUS_DEFAULT.getId());
		params.put("eqStatus", ShippingAddressStatusEnum.STATUS_NOT_DELETE.getId());
		
		PageList<FollowedShippingAddressWithAreaCode> addressList = userShippingAddressTemporaryDao.selectByMap(params, false);
		if(addressList.size() != 0) {
			address = addressList.get(0);
		} else {
			params.remove("eqIsDefault");
			addressList = userShippingAddressTemporaryDao.selectByMap(params, false);
			if(addressList.size() != 0) {
				address = addressList.get(0); 
			}
		}
		parseFollowedAddressArea(address);
		return address;
	}
	 
	 /**
     * 获取详细地址id，省、市、区id，并返回给userShippingAddress对象
     * @param address
     */
    protected void parseAddressArea(UserShippingAddressWithAreaCode address) {
    	if(null != address) {
	    	address.setProvinceId(address.getAreaId().substring(0, 2));
	    	address.setCityId(address.getAreaId().substring(0, 4));
	    	address.setDistrictId(address.getAreaId());
    	}
    }
    /**
     * 获取详细地址id，省、市、区id，并返回给userShippingAddress对象
     * @param address
     */
    protected void parseFollowedAddressArea(FollowedShippingAddressWithAreaCode address) {
    	if(null != address) {
    		address.setProvinceId(address.getAreaId().substring(0, 2));
    		address.setCityId(address.getAreaId().substring(0, 4));
    		address.setDistrictId(address.getAreaId());
    	}
    }
    
    protected String createAccountName() {
		String userName = "";
		String pre = "ehy";
	    boolean flag = false;
	    Map<String, Object> param = new HashMap<String, Object>();
	    int count = 0;
		do {
	       userName = pre + StringUtil.getRandomString(3) + new Date().getTime();
	       param.put("eqAccountName", userName);
	       count = userAccountInfoDao.selectCountByMap(param);
	       if (count > 0) {
	    	   flag = false;
	       } else {
	    	   flag = true;
	       }
		} while (!flag);
		return userName;
	}
	
    protected String creatAccountNameByEmail(String email) {
		String preEmail = email.substring(0, email.indexOf("@"));
		Pattern pattern = Pattern.compile("[0-9]*"); 
		String userName = "";
		if (pattern.matcher(preEmail).matches()) {
	    	userName = preEmail + "的好药师";
	    } else {
	    	userName = preEmail + RandomUtil.RandomString(4);
	    }
		String postfix = "的好药师";
	    boolean flag = false;
	    Map<String, Object> param = new HashMap<String, Object>();
	    int count = 0;
	    param.put("eqAccountName", userName);
	    count = userAccountInfoDao.selectCountByMap(param);
	    if (count == 0) {
	    	return userName;
	    }
		do {
	       userName = RandomUtil.RandomString(4) + postfix;
	       param.put("eqAccountName", userName);
	       count = userAccountInfoDao.selectCountByMap(param);
	       if (count > 0) {
	    	   flag = false;
	       } else {
	    	   flag = true;
	       }
		} while (!flag);
		return userName;
	}
	
    protected String creatAccountNameByPhone(String username) {
		String postfix = "的好药师";
		String userName = username + postfix;
	    boolean flag = false;
	    Map<String, Object> param = new HashMap<String, Object>();
	    int count = 0;
	    param.put("eqAccountName", userName);
	    count = userAccountInfoDao.selectCountByMap(param);
	    if (count == 0) {
	    	return userName;
	    }
		do {
	       userName = RandomUtil.RandomString(4) + postfix;
	       param.put("eqAccountName", userName);
	       count = userAccountInfoDao.selectCountByMap(param);
	       if (count > 0) {
	    	   flag = false;
	       } else {
	    	   flag = true;
	       }
		} while (!flag);
		return userName;
	}
	

	/**
	 * 联合登陆通过开放平台昵称注册，返回可用的用户名
	 * @param username
	 * @return
	 */
	protected String getLegalUserName(String username){
		//比对用户名是否合法，如果不合法，则赋予一个默认值。
//		username = username.replaceAll("[^a-zA-Z_\u4e00-\u9fa5]", "");
		if (Pattern.matches("^[a-zA-Z0-9_\u4e00-\u9fa5]+$", username)) {
			if(username.length() < 2){//如果用户名不足2位则在用户名后面加1
				username = username + "1";
			}
			if(username.length() > 20){//如果用户名超过20位则截取前18位
				username = username.substring(15);
			}
			String result = username;
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("eqAccountName", username);
			int count = userAccountInfoDao.selectCountByMap(param);
			while(count>0){//如果存在相同的账号，则通过在账号后面依次加数字进行区分
				result = username + RandomUtil.RandomString(5); 
				param.clear();
				param.put("eqAccountName", result);
				count = userAccountInfoDao.selectCountByMap(param);
			}
			username = result; 
		} else {//如果用户名为空，则赋一个默认值
			username = createAccountName();
		}
		return username;
	}
	
    protected UserAccountInfo insertUser(String accountName, String email, String phone, Integer applicablePlatformId, String expandCode,
			String passwd) {
		UserAccountInfo userAccountInfo = new UserAccountInfo();
		userAccountInfo.setAccountName(accountName);
		userAccountInfo.setEmail(email);
		if (!StringUtil.isEmpty(email)) {
			userAccountInfo.setIsEmailValid(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		}
		userAccountInfo.setPhone(phone);
		if (!StringUtil.isEmpty(phone)) {
			userAccountInfo.setIsPhoneValid(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		}
		userAccountInfo.setApplicablePlatformId(applicablePlatformId);
		userAccountInfo.setExpandCode(expandCode);
		if (!StringUtil.isEmpty(passwd)) {
			userAccountInfo.setPasswd(StringUtil.md5(passwd));
		}
		userAccountInfo.setIsAccountValid(UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
		userAccountInfo.setIsAccountActive(UserAccountInfoStatusEnum.STATUS_NORMAL.getId());
		Date date = new Date();
		userAccountInfo.setCreateTime(date.getTime());
		userAccountInfoDao.insert(userAccountInfo);
		return userAccountInfo;
	}
    
    protected void initializeOther(UserAccountInfo userAccountInfo, String nickname, String... realName) {
		UserBaseInfo userBaseInfo = new UserBaseInfo();
		UserLevelInfo userLevelInfo = new UserLevelInfo();
		userBaseInfo.setId(userAccountInfo.getId());
		if (realName != null && realName.length > 0) {
			userBaseInfo.setRealName(realName[0]);
		}
		if (StringUtil.isEmpty(nickname)) {
			if(!StringUtil.isEmpty(userAccountInfo.getAccountName()))
				userBaseInfo.setNickName(userAccountInfo.getAccountName());
		} else {
			userBaseInfo.setNickName(nickname);
		}
		if (!StringUtil.isEmpty(userAccountInfo.getPhone())) {
			JSONArray jsonArray = new JSONArray();
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("isVerify", 1);
			jsonObject.put("phone", userAccountInfo.getPhone());
			jsonObject.put("isImport", 0);
			jsonArray.add(jsonObject);
			userBaseInfo.setOrderPhone(jsonArray.toJSONString());
		}
		userLevelInfo.setId(userAccountInfo.getId());
		userLevelInfo.setLevelId(UserTypeEnum.GENERAL.getType());
		userBaseInfoDao.insert(userBaseInfo);
		userLevelInfoDao.insert(userLevelInfo);
	}
    
    protected void verifyParams(String userName, Map<String, Object> params)  throws Exception {
		
		String email = "";
		String phone = "";
		String accountName = "";
		if (StringUtil.isEmail(userName)) {
			email = userName;
		} else if (StringUtil.isMobilePhone(userName)) {
			phone = userName;
		} else {
			accountName = userName;
		}
		if (!StringUtil.isEmpty(accountName)) {
			if (accountName.length() < 2 || accountName.length() > 20) {
				throw new ServiceOperationException("用户名的长度在2-20位");
			}
			if (!Pattern.matches("^[a-zA-Z0-9_\u4e00-\u9fa5]+$", accountName)) {
				throw new ServiceOperationException("用户名只能是中文，字母，数字，下划线组成");
			} 
		}
		if (!StringUtil.isEmpty(email) && !StringUtil.isEmail(email)) {
			throw new ServiceOperationException("邮箱格式有误");
		}
		if (!StringUtil.isEmpty(phone) && !StringUtil.isMobilePhone(phone)) {
			throw new ServiceOperationException("手机号码格式有误");
		}
		
		if (!StringUtil.isEmpty(accountName)) {
			params.put("eqAccountName", accountName);
		}
		if (!StringUtil.isEmpty(email)) {
			params.put("eqEmail", email);
			params.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			// 由于官网旧数据有用户用邮箱注册了，邮箱就是用户名，导致登录不了，- -! 要哭了
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count == 0) {
				params.clear();
				params.put("eqAccountName", email);
			}
		}
		if (!StringUtil.isEmpty(phone)) {
			params.put("eqPhone", phone);
			params.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
			// 由于官网旧数据有用户用手机注册了，手机号码就是用户名，导致登录不了，- -! 要哭了
			int count = userAccountInfoDao.selectCountByMap(params);
			if (count == 0) {
				params.clear();
				params.put("eqAccountName", phone);
			}
		}
	}
}
